class Float
  def round(places = 0) 
    ("%.0#{places}f" % self).to_f
  end
  
  def round_to_decimal(places = 0)
    if places == 0 
      self.round
    else
      multiplier = 10 ** places
      (multiplier * self).round.to_f / multiplier
    end
  end

  # makes it go out to 5 decimal places for pretty display
  def to_decimal_string
  	n = round(5).to_s
  	n.ljust 6+n.index("."), "0"
  end
end


class Array
	# useful for grouping an array of objects into multiple arrays based on a common attribute
	# Example:
	# >> my_array = ["cats", "dogs", "people", "things", "elephants", "computers", "cars", "1001"]
	# => ["cats", "dogs", "people", "things", "elephants", "computers", "cars", "1001"]
	# >> my_array.group_by "size"
	# => [["people", "things"], ["elephants", "computers"], ["cats", "dogs", "cars", "1001"]]
	# 
	# also can take a block - equal evaluation of the block determines grouping
	# Examples:
	# >> my_array.group_by { |a| a[0] }
	# => [["things"], ["cats", "computers", "cars"], ["1001"], ["dogs"], ["elephants"], ["people"]]
	#
	# >> [4, "foo", 500, "bar", 4.5].group_by { |a| a.is_a? Integer }
	# => [[4, 500], ["foo", "bar", 4.5]]
	#
	# >> [4, "foo", 500, "bar", 4.5].group_by { |a| a.to_s.size }
	# => [[4], ["foo", 500, "bar", 4.5]]
	
	def group_by(attribute = nil)
		arrays = {}
		for i in 0...size
			object = self[i]
			value = attribute ? object.send(attribute.to_sym) : yield(object)
			if arrays[value.to_s]
				arrays[value.to_s] << object
			else
				arrays[value.to_s] = [object]
			end
		end
		return arrays.values
	end
	
	# sum up some numbers in an array
	# just a friendlier version of the inject statement
	def sum
    return nil if self.empty?
		inject { |n, m| n += m }
	end
  
   # average of numbers in an array
  def average
    return nil if self.empty?
    sum / size
  end
	
end


